<template>
  <div class="study-overview">
    <el-row :gutter="20">
      <el-col :span="12">
        <!-- 各组主动回答问题次数表格及饼状图 -->
        <el-card class="chart-card">
          <div slot="header" class="clearfix">
            <span>各组主动回答问题次数</span>
          </div>
          <div class="chart-container">
            <div class="chart-table">
              <el-table :data="answerData" style="width: 100%" height="250">
                <el-table-column
                  prop="group"
                  label="组别"
                  width="80"
                ></el-table-column>
                <el-table-column
                  prop="count"
                  label="回答次数"
                  width="100"
                ></el-table-column>
                <el-table-column
                  prop="percentage"
                  label="百分比"
                ></el-table-column>
              </el-table>
              <div class="clearfix totalNumber">总回答人数: {{ totalAnswerCount }}</div>
            </div>
            <div class="chart" ref="answerPieChart"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <!-- 各组竞赛情况表格 -->
        <el-card class="chart-card">
          <div slot="header" class="clearfix">
            <span>各组竞赛情况</span>
          </div>
          <div class="chart-container">
            <el-table 
              :data="competitionData" 
              style="width: 100%" 
              height="300"
              :fit="true"
              border
              stripe
            >
              <el-table-column
                prop="group"
                label="组别"
                min-width="80"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                prop="name"
                label="姓名"
                min-width="100"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                prop="class"
                label="班级"
                min-width="80"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                prop="competitionsNum"
                label="竞赛次数"
                min-width="100"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                prop="awardsNum"
                label="获奖次数"
                min-width="100"
                show-overflow-tooltip
              ></el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="12">
        <!-- 各组图书馆情况柱状图 -->
        <el-card class="chart-card">
          <div slot="header" class="clearfix">
            <span>各组图书馆情况</span>
          </div>
          <div class="chart" ref="libraryBarChart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <!-- 各组作业评级登记柱状图 -->
        <el-card class="chart-card">
          <div slot="header" class="clearfix">
            <span>各组作业评级登记</span>
          </div>
          <div class="chart" ref="homeworkBarChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="24">
        <!-- xx成绩折线图 -->
        <el-card class="chart-card">
          <div slot="header" class="clearfix">
            <span>成绩折线图</span>
          </div>
          <div class="chart-buttons">
            <button
              v-for="(btn, idx) in subjectButtons"
              :key="btn.key"
              :class="['chart-btn', { active: activeSubjectIndex === idx }]"
              @click="switchSubject(idx)"
            >
              {{ btn.label }}
            </button>
          </div>
          <div class="chart" ref="scoreLineChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="24">
        <!-- 本月自主学术讲座表格 -->
        <el-card class="chart-card">
          <div slot="header" class="clearfix">
            <span>本月自主学术讲座</span>
          </div>
          <div class="chart-container">
            <el-table
              :data="lectureData"
              stripe
              style="width: 100%"
              height="300"
            >
              <el-table-column
                prop="name"
                label="姓名"
                width="100"
              ></el-table-column>
              <el-table-column
                prop="date"
                label="日期"
                width="120"
              ></el-table-column>
              <el-table-column
                prop="lecture"
                label="讲座名称"
                width="150"
              ></el-table-column>
              <el-table-column
                prop="class"
                label="班级"
                width="80"
              ></el-table-column>
              <el-table-column prop="group" label="组别"></el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="24">
        <!-- 各组晚加班情况表格及饼状图 -->
        <el-card class="chart-card">
          <div slot="header" class="clearfix">
            <span>各组晚加班情况</span>
          </div>
          <div class="chart-container">
            <div class="chart-table">
              <el-table :data="overtimeData" style="width: 100%" height="250">
                <el-table-column
                  prop="group"
                  label="组别"
                  width="80"
                ></el-table-column>
                <el-table-column
                  prop="count"
                  label="加班次数"
                  width="100"
                ></el-table-column>
                <el-table-column
                  prop="percentage"
                  label="百分比"
                ></el-table-column>
              </el-table>
              <div class="clearfix totalNumber">总加班人数: {{ totalOvertimeCount }}</div>
            </div>
            <div class="chart" ref="overtimePieChart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "StudyOverview",
  data() {
    return {
      // 各组主动回答问题次数数据
      answerData: [
        { group: "1组", count: 5, percentage: 15 },
        { group: "2组", count: 5, percentage: 15 },
        { group: "3组", count: 5, percentage: 15 },
      ],
      totalAnswerCount: 24, // 修改初始值为24
      constituenciesIndex: 0, // 默认显示组别一
      contestSituation: 0, // 默认显示组别一
      constituenciesTabs: [
        { name: "1 组", icon: "book" },
        { name: "2 组", icon: "book" },
        { name: "3 组", icon: "book" },
      ],
      // 各组竞赛情况数据
      competitionData: [],
      // 图书馆数据
      libraryData: [],
      // 作业评级数据
      homeworkData: [],
      // 成绩数据
      scoreData: [],
      // 讲座数据
      lectureData: [],
      // 晚加班数据
      overtimeData: [],
      totalOvertimeCount: 0,
      subjectButtons: [
        { label: '高等数学', key: '高等数学' },
        { label: '大学物理', key: '大学物理' },
        { label: '高等代数', key: '高等代数' }
      ],
      activeSubjectIndex: 0,
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    switchTab(index, val) {
      switch (val) {
        case "次数":
          this.constituenciesIndex = index;
          break;
        case "情况":
          this.contestSituation = index;
          break;
      }
    },
    
    // 获取所有数据
    async fetchData() {
      try {
        await Promise.all([
          this.fetchAnswerData(),
          this.fetchCompetitionData(),
          this.fetchLibraryData(),
          this.fetchHomeworkData(),
          this.fetchScoreData(),
          this.fetchLectureData(),
          this.fetchOvertimeData(),
        ]);

        // 初始化图表
        this.$nextTick(() => {
          this.initAnswerPieChart();
          this.initLibraryBarChart();
          this.initHomeworkBarChart();
          this.initScoreLineChart();
          this.initOvertimePieChart();
        });
      } catch (error) {
        console.error("Error fetching data:", error);
        this.$message.error("加载数据失败，请检查文件是否存在");
      }
    },

    // 获取竞赛数据
    async fetchCompetitionData() {
      try {
        const result = await this.$overviewapi.getCompetition();

        // 确保数据格式正确
        if (!result || !result.data || !Array.isArray(result.data)) {
          throw new Error("API返回数据格式不正确");
        }

        // 格式化数据
        this.competitionData = result.data.map((item) => ({
          group: item.groupName ? item.groupName + "组" : "未分组",
          name: item.name || "",
          class: item.classes || "",
          competitionsNum: item.competitionsNum || 0,
          awardsNum: item.awardsNum || 0
        }));
      } catch (error) {
        console.error("加载竞赛数据失败:", error);
        this.$message.error("加载竞赛数据失败，请检查API连接");
      }
    },

    // 获取回答问题数据
    async fetchAnswerData() {
      try {
        const result = await this.$overviewapi.getProactive();
        
        // 确保数据存在且格式正确
        if (!result || !result.data || typeof result.data !== 'object') {
          throw new Error('返回数据格式不正确');
        }

        const data = result.data;
        // 直接使用返回的数据格式，确保转换为数字
        const totalCount = Number(data.total_count) || 0;
        this.$set(this, 'totalAnswerCount', totalCount); // 使用Vue的$set确保响应式更新

        // 格式化数据
        this.answerData = [
          {
            group: "1组",
            count: Number(data.group1_count) || 0,
            percentage: totalCount > 0 ? ((Number(data.group1_count) / totalCount) * 100).toFixed(2) + "%" : "0%"
          },
          {
            group: "2组",
            count: Number(data.group_2_count) || 0,
            percentage: totalCount > 0 ? ((Number(data.group_2_count) / totalCount) * 100).toFixed(2) + "%" : "0%"
          },
          {
            group: "3组",
            count: Number(data.group_3_count) || 0,
            percentage: totalCount > 0 ? ((Number(data.group_3_count) / totalCount) * 100).toFixed(2) + "%" : "0%"
          }
        ];
      } catch (error) {
        console.error("加载回答问题数据失败:", error);
        this.$message.error("加载回答问题数据失败，请检查API连接");
      }
    },

    // 获取图书馆数据
    async fetchLibraryData() {
      try {
        const result = await this.$overviewapi.getLibrary();

        // 确保数据格式正确
        if (!result || !result.data || !Array.isArray(result.data)) {
          throw new Error("API返回数据格式不正确");
        }

        // 格式化数据
        this.libraryData = result.data.map((item) => ({
          group: item.groupName ? item.groupName + "组" : "未分组",
          count: Number(item.countStudent) || 0
        }));
      } catch (error) {
        console.error("加载图书馆数据失败:", error);
        this.$message.error("加载图书馆数据失败，请检查API连接");
        // 使用空数组作为回退
        this.libraryData = [];
      }
    },

    // 获取作业评级数据
    async fetchHomeworkData() {
      try {
        const result = await this.$overviewapi.getHomeworkrating();

        // 确保数据格式正确
        if (!result || !result.data || !Array.isArray(result.data)) {
          throw new Error("API返回数据格式不正确");
        }

        // 按组别和评级统计作业情况
        const groupGrades = {};
        result.data.forEach((item) => {
          const group = item.groupName || "未分组";
          const grade = item.homeworkGrade || "未评级";

          if (!groupGrades[group]) {
            groupGrades[group] = {};
          }

          if (!groupGrades[group][grade]) {
            groupGrades[group][grade] = 0;
          }

          groupGrades[group][grade] = Number(item.countStudent) || 0;
        });

        // 格式化数据
        this.homeworkData = Object.entries(groupGrades).map(
          ([group, grades]) => {
            return {
              group: group + "组",
              grades,
            };
          }
        );
      } catch (error) {
        console.error("加载作业评级数据失败:", error);
        this.$message.error("加载作业评级数据失败，请检查API连接");
        // 使用空数组作为回退
        this.homeworkData = [];
      }
    },

    // 获取成绩数据
    async fetchScoreData() {
      try {
        const result = await this.$overviewapi.getScoreComparison();

        // 确保数据格式正确
        if (!result || !result.data || !Array.isArray(result.data)) {
          throw new Error("API返回数据格式不正确");
        }

        // 直接使用返回的数据
        this.scoreData = result.data;
      } catch (error) {
        console.error("加载成绩数据失败:", error);
        this.$message.error("加载成绩数据失败，请检查API连接");
        // 使用空数组作为回退
        this.scoreData = [];
      }
    },

    // 获取讲座数据
    async fetchLectureData() {
      try {
        const result = await this.$overviewapi.getLecture({ pageNum: 1, pageSize: 5 });

        // 确保数据格式正确
        if (!result || result.code !== "200" || !Array.isArray(result.data)) {
          throw new Error("API返回数据格式不正确");
        }

        // 格式化数据
        this.lectureData = result.data.map((item) => ({
          name: item.name || "",
          date: this.formatDate(item.lectureDate),
          lecture: item.topic || "",
          class: item.classes || "",
          group: item.groupName ? item.groupName + "组" : "",
        }));
      } catch (error) {
        console.error("加载讲座数据失败:", error);
        this.$message.error("加载讲座数据失败，请检查API连接");
        // 使用空数组作为回退
        this.lectureData = [];
      }
    },

    // 获取晚加班数据
    async fetchOvertimeData() {
      try {
        const result = await this.$overviewapi.getOvertime();
        
        // 确保数据存在且格式正确
        if (!result || result.code !== "200" || !result.data) {
          throw new Error('返回数据格式不正确');
        }

        const data = result.data;
        // 直接使用返回的数据格式，确保转换为数字
        const totalCount = Number(data.total_count) || 0;
        this.$set(this, 'totalOvertimeCount', totalCount); // 使用Vue的$set确保响应式更新

        // 格式化数据
        this.overtimeData = [
          {
            group: "1组",
            count: Number(data.group1_count) || 0,
            percentage: totalCount > 0 ? ((Number(data.group1_count) / totalCount) * 100).toFixed(2) + "%" : "0%"
          },
          {
            group: "2组",
            count: Number(data.group_2_count) || 0,
            percentage: totalCount > 0 ? ((Number(data.group_2_count) / totalCount) * 100).toFixed(2) + "%" : "0%"
          },
          {
            group: "3组",
            count: Number(data.group_3_count) || 0,
            percentage: totalCount > 0 ? ((Number(data.group_3_count) / totalCount) * 100).toFixed(2) + "%" : "0%"
          }
        ];
      } catch (error) {
        console.error("加载晚加班数据失败:", error);
        this.$message.error("加载晚加班数据失败，请检查API连接");
      }
    },

    // 初始化回答问题饼图
    initAnswerPieChart() {
      const chartDom = this.$refs.answerPieChart;
      const myChart = echarts.init(chartDom);

      const option = {
        backgroundColor: "transparent",
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        legend: {
          orient: "vertical",
          left: 10,
          textStyle: {
            color: "#d3d6dd",
          },
          data: this.answerData.map((item) => item.group),
        },
        series: [
          {
            name: "回答次数",
            type: "pie",
            radius: ["50%", "70%"],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: "center",
              color: "#d3d6dd",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "18",
                fontWeight: "bold",
                color: "#68d8fe",
              },
            },
            labelLine: {
              show: false,
            },
            itemStyle: {
              borderColor: "rgba(19, 25, 47, 0.6)",
              borderWidth: 1,
            },
            data: this.answerData.map((item) => ({
              value: item.count,
              name: item.group,
            })),
          },
        ],
      };

      myChart.setOption(option);

      // 响应窗口大小变化
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },

    // 初始化图书馆柱状图
    initLibraryBarChart() {
      const chartDom = this.$refs.libraryBarChart;
      const myChart = echarts.init(chartDom);

      const option = {
        backgroundColor: "transparent",
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: this.libraryData.map((item) => item.group),
          axisLine: {
            lineStyle: {
              color: "rgba(104, 216, 254, 0.5)",
            },
          },
          axisLabel: {
            color: "#d3d6dd",
          },
        },
        yAxis: {
          type: "value",
          name: "人次",
          nameTextStyle: {
            color: "#d3d6dd",
          },
          axisLine: {
            lineStyle: {
              color: "rgba(104, 216, 254, 0.5)",
            },
          },
          axisLabel: {
            color: "#d3d6dd",
          },
          splitLine: {
            lineStyle: {
              color: "rgba(104, 216, 254, 0.2)",
            },
          },
        },
        series: [
          {
            name: "图书馆使用次数",
            type: "bar",
            data: this.libraryData.map((item) => item.count),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(104, 216, 254, 0.8)" },
                { offset: 1, color: "rgba(104, 216, 254, 0.3)" },
              ]),
              borderRadius: 4,
            },
          },
        ],
      };

      myChart.setOption(option);

      // 响应窗口大小变化
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },

    // 初始化作业评级柱状图
    initHomeworkBarChart() {
      const chartDom = this.$refs.homeworkBarChart;
      const myChart = echarts.init(chartDom);

      // 获取所有评级类型
      const allGrades = new Set();
      this.homeworkData.forEach((item) => {
        Object.keys(item.grades).forEach((grade) => {
          allGrades.add(grade);
        });
      });

      const gradesList = Array.from(allGrades);

      // 颜色映射
      const colorMap = {
        "A+": "#e74c3c",
        A: "#3498db",
        B: "#2ecc71",
        C: "#f39c12",
        阅: "#9b59b6",
      };

      // 准备系列数据
      const series = gradesList.map((grade) => {
        return {
          name: grade,
          type: "bar",
          stack: "total",
          label: {
            show: true,
            color: "#fff",
          },
          emphasis: {
            focus: "series",
          },
          itemStyle: {
            color: colorMap[grade] || "#68d8fe",
          },
          data: this.homeworkData.map((item) => item.grades[grade] || 0),
        };
      });

      const option = {
        backgroundColor: "transparent",
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        legend: {
          data: gradesList,
          textStyle: {
            color: "#d3d6dd",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: this.homeworkData.map((item) => item.group),
          axisLine: {
            lineStyle: {
              color: "rgba(104, 216, 254, 0.5)",
            },
          },
          axisLabel: {
            color: "#d3d6dd",
          },
        },
        yAxis: {
          type: "value",
          name: "数量",
          nameTextStyle: {
            color: "#d3d6dd",
          },
          axisLine: {
            lineStyle: {
              color: "rgba(104, 216, 254, 0.5)",
            },
          },
          axisLabel: {
            color: "#d3d6dd",
          },
          splitLine: {
            lineStyle: {
              color: "rgba(104, 216, 254, 0.2)",
            },
          },
        },
        series: series,
      };

      myChart.setOption(option);

      // 响应窗口大小变化
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },

    // 初始化成绩折线图
    initScoreLineChart() {
      const subjectKey = this.subjectButtons[this.activeSubjectIndex].key;
      const subjectData = this.scoreData.filter(item => item.subject === subjectKey);
      const examNames = subjectData.map(item => item.examName);
      const allAvgData = subjectData.map(item => Number(item.allAvg).toFixed(2));
      const groupOneData = subjectData.map(item => Number(item.groupOneAavg).toFixed(2));
      const groupTwoData = subjectData.map(item => Number(item.groupTwoAavg).toFixed(2));
      const groupThreeData = subjectData.map(item => Number(item.groupThreeAavg).toFixed(2));

      // 计算所有数据的最小值和最大值
      const allData = [...allAvgData, ...groupOneData, ...groupTwoData, ...groupThreeData];
      const minValue = Math.min(...allData);
      const maxValue = Math.max(...allData);

      // 计算合适的步长
      const range = maxValue - minValue;
      let interval = 5; // 默认步长
      if (range <= 10) {
        interval = 2;
      } else if (range <= 20) {
        interval = 5;
      } else {
        interval = 10;
      }

      // 计算合适的y轴范围
      const min = Math.floor(minValue / interval) * interval;
      const max = Math.ceil(maxValue / interval) * interval;

      const option = {
        backgroundColor: "transparent",
        tooltip: {
          trigger: "axis",
          formatter: function(params) {
            let result = params[0].axisValue + '<br/>';
            params.forEach(param => {
              result += param.seriesName + ': ' + param.value + '<br/>';
            });
            return result;
          }
        },
        legend: {
          data: ['总平均分', '第一组平均分', '第二组平均分', '第三组平均分'],
          textStyle: {
            color: '#d3d6dd'
          }
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: examNames,
          axisLine: {
            lineStyle: {
              color: "rgba(104, 216, 254, 0.5)",
            },
          },
          axisLabel: {
            color: "#d3d6dd",
            rotate: 45,
            interval: 0
          },
        },
        yAxis: {
          type: "value",
          name: "平均分",
          min: min,
          max: max,
          interval: interval,
          nameTextStyle: {
            color: "#d3d6dd",
          },
          axisLine: {
            lineStyle: {
              color: "rgba(104, 216, 254, 0.5)",
            },
          },
          axisLabel: {
            color: "#d3d6dd",
            formatter: function(value) {
              return value.toFixed(1);
            }
          },
          splitLine: {
            lineStyle: {
              color: "rgba(104, 216, 254, 0.2)",
            },
          },
        },
        series: [
          {
            name: '总平均分',
            type: 'line',
            data: allAvgData,
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#ff4d4f'
            },
            lineStyle: {
              color: '#ff4d4f',
              width: 3
            }
          },
          {
            name: '第一组平均分',
            type: 'line',
            data: groupOneData,
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#ff9f7f'
            },
            lineStyle: {
              color: '#ff9f7f',
              width: 3
            }
          },
          {
            name: '第二组平均分',
            type: 'line',
            data: groupTwoData,
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#95a2ff'
            },
            lineStyle: {
              color: '#95a2ff',
              width: 3
            }
          },
          {
            name: '第三组平均分',
            type: 'line',
            data: groupThreeData,
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#59c4e6'
            },
            lineStyle: {
              color: '#59c4e6',
              width: 3
            }
          }
        ]
      };

      const chartDom = this.$refs.scoreLineChart;
      const myChart = echarts.init(chartDom);
      myChart.setOption(option);

      // 响应窗口大小变化
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },

    // 初始化晚加班饼图
    initOvertimePieChart() {
      const chartDom = this.$refs.overtimePieChart;
      const myChart = echarts.init(chartDom);

      const option = {
        backgroundColor: "transparent",
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        legend: {
          orient: "vertical",
          left: 10,
          textStyle: {
            color: "#d3d6dd",
          },
          data: this.overtimeData.map((item) => item.group),
        },
        series: [
          {
            name: "加班次数",
            type: "pie",
            radius: "70%",
            center: ["60%", "50%"],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: "outside",
              formatter: "{b}: {c} ({d}%)",
              color: "#d3d6dd",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "18",
                fontWeight: "bold",
                color: "#68d8fe",
              },
            },
            labelLine: {
              show: true,
              length: 20,
              length2: 20,
              lineStyle: {
                color: "rgba(104, 216, 254, 0.5)",
              },
            },
            itemStyle: {
              borderColor: "rgba(19, 25, 47, 0.6)",
              borderWidth: 1,
            },
            data: this.overtimeData.map((item) => ({
              value: item.count,
              name: item.group,
            })),
          },
        ],
      };

      myChart.setOption(option);

      // 响应窗口大小变化
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },

    // 解析CSV文件
    parseCSV(csvText) {
      // 处理可能的BOM标记和不同的行结束符
      const cleanText = csvText.replace(/^\uFEFF/, "");

      // 合并所有内容为一个字符串，处理可能的换行问题
      const allText = cleanText.replace(/\r?\n\s*/g, "\n");
      const lines = allText.split("\n");

      if (lines.length <= 1) {
        console.warn("CSV文件为空或只有标题行");
        return [];
      }

      // 获取头部列名
      const headers = lines[0].split(",").map((header) => header.trim());

      // 处理数据行
      const records = [];
      for (let i = 1; i < lines.length; i++) {
        const line = lines[i].trim();
        if (!line) {
          continue; // 跳过空行
        }

        const values = line.split(",");
        if (values.length < headers.length) {
          continue; // 跳过不完整的行
        }

        const record = {};
        headers.forEach((header, index) => {
          // 确保所有值都被正确处理
          record[header] = values[index] ? values[index].trim() : "";
        });

        records.push(record);
      }

      return records;
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return "";

      // 假设日期格式为 YYYYMMDD
      if (dateStr.length === 8) {
        const year = dateStr.substring(0, 4);
        const month = dateStr.substring(4, 6);
        const day = dateStr.substring(6, 8);
        return `${year}-${month}-${day}`;
      }

      return dateStr;
    },

    switchSubject(idx) {
      this.activeSubjectIndex = idx;
      this.initScoreLineChart();
    },
  },
};
</script>

<style lang="scss" scoped>
.clearfix {
  font-size: 22px;
  font-weight: bold;
  color: #68d8fe;
}
.totalNumber {
  font-size: 22px;
  display: flex;
  height: 50px;
  align-items: center;
}
:deep(.el-table) {
  background-color: transparent;
  height: 100%;
  border: 2px solid #68d8fe;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(104, 216, 254, 0.3);

  th {
    background: linear-gradient(to bottom, #2c3e50, #1d2127) !important;
    border-bottom: 2px solid #68d8fe;
    border-right: 1px solid #68d8fe;
    font-weight: bold;
    padding: 15px 0;
    font-size: 16px !important;
    color: #68d8fe !important;
  }

  td {
    background-color: rgba(29, 33, 39, 0.8);
    border-bottom: 1px solid #68d8fe;
    border-right: 1px solid #68d8fe;
    color: #fff;
    padding: 12px 0;
    transition: background-color 0.2s ease;
  }

  .even-row td {
    background-color: rgba(29, 33, 39, 0.8);
  }

  .odd-row td {
    background-color: rgba(19, 25, 47, 0.8);
  }

  .el-table__row:hover > td {
    background-color: rgba(45, 50, 62, 0.9) !important;
  }

  .el-table__header-wrapper {
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
    overflow: hidden;
  }

  .el-table__body-wrapper {
    border-bottom-left-radius: 8px;
    border-bottom-right-radius: 8px;
    overflow-y: auto !important;
    overflow-x: hidden;
    max-height: 100%;
    scrollbar-width: thin;
    scrollbar-color: #68d8fe #1d2127;

    &::-webkit-scrollbar {
      width: 8px;
    }

    &::-webkit-scrollbar-track {
      background: #1d2127;
      border-radius: 4px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #68d8fe;
      border-radius: 4px;
      border: 2px solid #1d2127;
    }
  }

  // Remove last column's right border
  th:last-child,
  td:last-child {
    border-right: none;
  }

  // Fix border issues
  &::before {
    display: none;
  }

  .el-table__fixed::before,
  .el-table__fixed-right::before {
    display: none;
  }
}
.study-overview {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  max-height: 100vh;
  border: 1px solid rgba(104, 216, 254, 0.3);
  border-radius: 8px;
  background-color: rgba(19, 25, 47, 0.4);
}
.sub-tabs {
  display: flex;
  margin-bottom: 15px;
  background-color: rgba(19, 25, 47, 0.4);
  border-radius: 4px;
  padding: 3px;
  overflow-x: auto;
  width: fit-content;

  .sub-tab-item {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 8px 12px;
    margin: 0 3px;
    border-radius: 4px;
    cursor: pointer;
    white-space: nowrap;
    transition: all 0.3s ease;

    &:hover {
      background-color: rgba(104, 216, 254, 0.1);
    }

    &.active {
      background-color: rgba(104, 216, 254, 0.2);
      border-bottom: 2px solid #68d8fe;
    }

    .sub-tab-icon {
      font-size: 14px;
      color: #68d8fe;
      margin-right: 6px;
    }

    .sub-tab-text {
      font-size: 13px;
      color: #d3d6dd;
    }
  }
}
.chart-card {
  width: 100%;
  margin-bottom: 20px;
  background-color: rgba(104, 216, 254, 0.1) !important;
  border: 1px solid rgba(104, 216, 254, 0.5) !important;
  border-radius: 8px;
}

.chart-card >>> .el-card__header {
  background-color: rgba(104, 216, 254, 0.2);
  border-bottom: 1px solid rgba(104, 216, 254, 0.5);
  color: #68d8fe;
  font-weight: bold;
}

.chart-card >>> .el-card__body {
  background-color: transparent;
}

.chart-container {
  display: flex;
  width: 100%;
  flex-direction: column;
  overflow: hidden;
}

.chart-table {
  margin-bottom: 20px;
}

.chart-table >>> .el-table {
  background-color: transparent !important;
  color: #ffffff;
  font-weight: 500;
}

.chart-table >>> .el-table th {
  background-color: rgba(104, 216, 254, 0.3) !important;
  color: #68d8fe;
  font-weight: bold;
  border-bottom: 1px solid rgba(104, 216, 254, 0.5) !important;
}

.chart-table >>> .el-table td {
  background-color: transparent !important;
  border-bottom: 1px solid rgba(104, 216, 254, 0.3) !important;
}

.chart-table
  >>> .el-table--striped
  .el-table__body
  tr.el-table__row--striped
  td {
  background-color: rgba(104, 216, 254, 0.05) !important;
}

.chart-table >>> .el-table__body tr.hover-row > td {
  background-color: rgba(104, 216, 254, 0.1) !important;
}

.chart {
  height: 300px;
}

@media (min-width: 768px) {
  .chart-container {
    flex-direction: row;
  }

  .chart-table {
    flex: 1;
    margin-right: 20px;
    margin-bottom: 0;
  }

  .chart {
    flex: 1;
  }
}

:deep(.el-table) {
  width: 100%;
  .el-table__body-wrapper {
    overflow-x: auto;
  }
  .el-table__header-wrapper {
    overflow-x: auto;
  }
}

:deep(.el-table__body) {
  width: 100% !important;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell) {
  background: #343434;
}

.chart-buttons {
  display: flex;
  margin-bottom: 15px;
  margin-left: 20px;

  .chart-btn {
    background-color: rgba(19, 25, 47, 0.6);
    border: 1px solid rgba(104, 216, 254, 0.3);
    color: #d3d6dd;
    padding: 6px 12px;
    margin-right: 10px;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
    outline: none;

    &:hover {
      background-color: rgba(104, 216, 254, 0.1);
    }

    &.active {
      background-color: rgba(104, 216, 254, 0.2);
      border-color: #68d8fe;
      color: #68d8fe;
    }
  }
}
</style>
